package posts

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostsListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取香评列表,首页多香评展示
func NewGetPostsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostsListLogic {
	return &GetPostsListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 香评列表 ##25.03.22## 历史遗留文件，暂不处理
func (l *GetPostsListLogic) GetPostsList(
	req *types.PostsListReq,
	headers *[]*types.Header,
) (*types.PostsListResp, error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var uid uint64
	if req.UserId != nil && *req.UserId > 0 {
		uid = *req.UserId
	} else {
		uid = userId
	}
	var private bool = true
	if uid != userId {
		private = false
	}

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var filters []string
	filters = append(filters, "ForumId,equalTo:"+strconv.FormatInt(l.svcCtx.Config.Query.PostForumId, 10))

	preload := "forumPost:Id,AuthorId,ParentId"
	eagerLoad := "forumPost:forumMedia,forumPostMeta"
	if req.ParentId != nil && *req.ParentId > 0 { // 指定香水
		private = false // 大家的香评
		preload += ",AuthorName,AuthorAvatar,AuthorIp,AuthorLevel"
		eagerLoad += ",total"
		filters = append(filters, "ParentId,equalTo:"+strconv.FormatUint(*req.ParentId, 10))
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	} else if private { // 我的香评
		preload += ",Status"
		filters = append(filters, "AuthorId,equalTo:"+strconv.FormatUint(uid, 10))
		filters = append(filters, "Status,notEqualTo:"+strconv.FormatInt(int64(globalkey.StatusDeleted), 10))
	} else { // 别人的香评
		filters = append(filters, "AuthorId,equalTo:"+strconv.FormatUint(uid, 10))
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	}
	//ContentHtml
	preload += ",PostTitle,CommentStatus,CreatedAt;forumMedia:Id,Uid,Url,Thumbnail;forumPostMeta:likeCount,collectCount"

	var sorter *string
	if req.Sorter != nil {
		sorter = pointy.GetPointer(strings.TrimSpace(*req.Sorter))
	}
	res, err := l.svcCtx.ForumRpc.GetPostsList(l.ctx, &forumclient.PostsListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     sorter,
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
		WithMedia:  req.WithMedia,
		WithMeta:   req.WithMeta,
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}
	resp := &types.PostsListResp{
		BaseListInfo: types.BaseListInfo{
			Total:           res.Total,
			Current:         page,
			PageSize:        pageSize,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			var photos []*types.MediaInfo
			if len(v.Media) > 0 {
				for _, m := range v.Media {
					var url string
					if m.Url != nil && len(*m.Url) > 0 {
						url = *m.Url
					}
					if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
						url = *m.Uri
					}
					var thumbnail *bool
					if m.Thumbnail != nil {
						thumbnail = pointy.GetPointer(*m.Thumbnail > 0)
					}
					photos = append(photos, &types.MediaInfo{
						Uid:       m.Uid,
						Id:        m.Id,
						Url:       pointy.GetPointer(url),
						Thumbnail: thumbnail,
						AltText:   m.AltText,
						Details:   m.MetaData,
					})
				}
			}
			var meta []*types.MetaInfo
			var likeCount int
			var collectCount int
			if len(v.Meta) > 0 {
				for _, m := range v.Meta {
					if m.Key == nil || m.Value == nil || len(strings.TrimSpace(*m.Key)) == 0 || len(strings.TrimSpace(*m.Value)) == 0 {
						continue
					}
					key := strings.TrimSpace(*m.Key)
					val := strings.TrimSpace(*m.Value)
					if key == "_like_count" {
						likeCount, _ = strconv.Atoi(val)
					}
					if key == "_collect_count" {
						collectCount, _ = strconv.Atoi(val)
					}
					meta = append(meta, &types.MetaInfo{
						Id:    m.Id,
						Key:   pointy.GetPointer(key),
						Value: pointy.GetPointer(val),
					})
				}

			}
			resp.List = append(resp.List, &types.PostsInfo{
				PostId:         v.Id,
				ForumId:        v.ForumId,
				ParentId:       v.ParentId,
				AuthorId:       v.AuthorId,
				AuthorNickname: v.AuthorNickname,
				AuthorAvatar:   v.AuthorAvatar,
				AuthorIp:       v.AuthorIP,
				PostTitle:      v.PostTitle,
				PostContent:    v.PostContent,
				PostStatus:     v.Status,
				CommentStatus:  v.CommentStatus,
				PhotoCount:     v.PhotoCount,
				Photos:         photos,
				Meta:           meta,
				LikeCount:      pointy.GetPointer(uint64(likeCount)),
				CollectCount:   pointy.GetPointer(uint64(collectCount)),
				CreatedAt:      v.CreatedAt,
				UpdatedAt:      v.UpdatedAt,
				DeletedAt:      v.DeletedAt,
			})
		}
	}

	//if private && req.New != nil && *req.New {
	//	var userMeta []*userclient.UserMetaInfo
	//	userMeta = append(userMeta, &userclient.UserMetaInfo{
	//		Key:   pointy.GetPointer(mqueuex.UserStatisticForumReviewNew), // "_review_new_status"
	//		Value: pointy.GetPointer("0"),
	//	})
	//	l.svcCtx.UserRpc.SetUserMeta(l.ctx, &userclient.SetUserMetaReq{
	//		UserId:   pointy.GetPointer(userId),
	//		UserMeta: userMeta,
	//	})
	//}

	return resp, nil
}
